package com.changgou.goods.service.impl;

import com.changgou.goods.dao.BrandMapper;
import com.changgou.goods.service.BrandService;
import com.changgou.pojo.Brand;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * @Author: cxy
 * @Date: 2020/10/30 11:12
 * @Desc: 无
 * @Version: 1.0.0
 */
@Service
public class BrandServiceImpl implements BrandService {

    /**
     * 需要精确查询的字段
     */
    private static final String EXACT_SEARCH_FIELD_LETTER = "letter";


    @Autowired
    private BrandMapper brandMapper;

    @Override
    public List<Brand> findAll() {
        return brandMapper.selectAll();
    }

    @Override
    public Brand findById(int intValue) {
        return brandMapper.selectByPrimaryKey(intValue);
    }

    @Override
    public void addBrand(Brand brand) {
        brandMapper.insertSelective(brand);
    }

    @Override
    public void updateBrand(Brand brand) {
        brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public void deleteBrand(Integer id) {
        brandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Page<Brand> selectPageAndCondition(Map<String, String> condition, int pageNo, int pageSize) {
        // 分页器进行分页
        PageHelper.startPage(pageNo, pageSize);

        // 条件查询
        Example example = new Example(Brand.class);

        // 结合使用, COUNT聚合函数
        // example.setCountProperty();
        // brandMapper.selectCountByExample()
        // ORDER BY, ASC和DESC也含在传入的参数里
        // example.setOrderByClause();

        // Example只能当作条件, 不能查询条件
        Example.Criteria criteria = example.createCriteria();

        // 构建查询条件字段
        // 里面可能包含精确查询的字段
        if(!CollectionUtils.isEmpty(condition)){
            condition.forEach((k, v) -> {
                if(!StringUtils.isEmpty(k)){
                    if(StringUtils.equals(k, EXACT_SEARCH_FIELD_LETTER)){
                        criteria.andEqualTo(k, v);
                    }else{
                        String likeVal = "%" + v + "%";
                        criteria.andLike(k, likeVal);
                    }
                }
            });
        }

        List<Brand> brandList = brandMapper.selectByExample(example);

        // Page也是一个List
        return (Page<Brand>)brandList;
    }
}
